package com.ics.cmsadmin.modules.basic.service.impl;

import com.ics.cmsadmin.frame.core.annotation.ClearDbMember;
import com.ics.cmsadmin.frame.core.bean.PageBean;
import com.ics.cmsadmin.frame.core.bean.PageResult;
import com.ics.cmsadmin.frame.core.enums.CacheGroupEnum;
import com.ics.cmsadmin.modules.basic.bean.VideoBean;
import com.ics.cmsadmin.modules.basic.dao.VideoDao;
import com.ics.cmsadmin.modules.basic.service.VideoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;


@Service
public class VideoServiceImpl implements VideoService {

    private String userId = "30fe77e88f";
    private String secretKey = "A5070CK7yS";

    @Resource
    private VideoDao videoDao;

    @Override
    public PageResult list(VideoBean t, PageBean page) {
        long count = videoDao.count(t);
        if (count == 0){
            return new PageResult();
        }
        page = page == null ? new PageBean() : page;
        return PageResult.getPage(count, videoDao.list(t, page));
    }

    @ClearDbMember(group = CacheGroupEnum.CACHE_COURSE)
    @Override
    public boolean insert(VideoBean t) {
        return videoDao.insert(t) == 1;
    }

    @ClearDbMember(group = CacheGroupEnum.CACHE_COURSE)
    @Override
    public boolean update(String id, VideoBean t) {
        return videoDao.update(id, t) == 1;
    }

    @ClearDbMember(group = CacheGroupEnum.CACHE_COURSE)
    @Override
    public boolean delete(String id) {
        return videoDao.delete(id) == 1;
    }

    @Override
    public Map<String, String> polyvAuth() {
        String readToken = "e09d63ef-3836-4895-8dcc-a7e50f1f0715";
        String writeToken = "8c9f9d4a-adb5-434d-8771-f6651cd44c83";
        String ts = System.currentTimeMillis() + "";
        String hash = getHashValue(ts + writeToken, "MD5");
        String sign = getHashValue(secretKey + ts, "MD5");
        Map<String, String> response = new HashMap<>();
        response.put("ts", ts);
        response.put("hash", hash);
        response.put("sign", sign);
        response.put("userId", userId);
        response.put("readToken", readToken);
        return response;
    }

    private String getHashValue(String msg, String algorithm) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        assert md != null;
        md.update(msg.getBytes());
        return new BigInteger(1, md.digest()).toString(16);
    }
}
